package com.yueya.common.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.jfinal.kit.PropKit;
import com.yueya.basic.dict.model.Dict;

public class UploadUtil {

	// 字典表category
	public static final String UPLOAD_SAVE_PATH = "attachment_upload_save_path";
	public static final String UPLOAD_VISIT_URL = "attachment_url";

	// 获取上传的访问URL
	public static String getUploadVisitUrl() {
		return Dict.dao.getValue(UPLOAD_VISIT_URL);
	}

	// 获取上传的保存PATH
	public static String getUploadSavePath() {
		return Dict.dao.getValue(UPLOAD_SAVE_PATH);
	}

	public static String getImageSavePath() {

		String savePath = "/image/";
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
		SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
		SimpleDateFormat sdf3 = new SimpleDateFormat("dd");
		String y = sdf1.format(new Date());
		String m = sdf2.format(new Date());
		String d = sdf3.format(new Date());

		savePath += y + "/" + m + "/" + d + "/";

		return savePath;
	}

	// private final int MAXSize = 50 * 1024 * 1024; // 50M
	// private String filedir = "E:/work/nginx-1.9.4/html/zgmz";// 指定用户训练视频文件上传路径

	// 上传图片
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map uploadImg(String fileName, String dir, byte[] file) {
		boolean flag = true;
		// String savePath=JFinal.me().getServletContext().getRealPath("/");
		String savePath = PropKit.use("saveurl.properties").get("rooturl");
		String path = "";
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		try {
			// //检查目录
			// File uploadDir = new File(savePath);
			// if(!uploadDir.isDirectory()){
			// return null;
			// }
			// //检查目录写权限
			// if(!uploadDir.canWrite()){
			// return null;
			// }
			String dirName = "attached/" + dir;
			// 创建文件夹
			savePath += dirName + "/";
			path += dirName + "/";
			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String ymd = sdf.format(new Date());
			savePath += ymd + "/";
			path += ymd + "/";
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			String name = generateFileName(fileName);
			path += name;
			File savedFile = new File(savePath, name);
			fos = new FileOutputStream(savedFile);
			bos = new BufferedOutputStream(fos);
			bos.write(file);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		Map map = new HashMap();
		map.put("flag", flag == true ? "1" : "0");
		map.put("savepath", path);
		return map;
	}

	public static Map<String, Object> uploadImg(String savePath, String fileName, String dir, byte[] file) {
		boolean flag = true;
		String path = "";
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String dirName = "attached/" + dir;
			savePath += dirName + "/";
			path += dirName + "/";
			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
			SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
			SimpleDateFormat sdf3 = new SimpleDateFormat("dd");
			// String ymd = sdf.format(new Date());
			String y = sdf1.format(new Date());
			String m = sdf2.format(new Date());
			String d = sdf3.format(new Date());
			// savePath += ymd + "/";
			// path += ymd + "/";

			savePath += y + "/" + m + "/" + d + "/";
			path += y + "/" + m + "/" + d + "/";

			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			String name = generateFileName(fileName);
			path += name;
			File savedFile = new File(savePath, name);

			fos = new FileOutputStream(savedFile);
			bos = new BufferedOutputStream(fos);
			bos.write(file);
			map.put("flag", flag == true ? "1" : "0");
			map.put("savepath", path);

		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}

		return map;
	}

	public static Map<String, Object> uploadFile(String savePath, String fileName, String dir, File file) {
		boolean flag = true;
		String path = "";
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String dirName = dir;
			savePath += dirName + "/";
			path += dirName + "/";
			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}

			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
			SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
			SimpleDateFormat sdf3 = new SimpleDateFormat("dd");
			String y = sdf1.format(new Date());
			String m = sdf2.format(new Date());
			String d = sdf3.format(new Date());

			savePath += y + "/" + m + "/" + d + "/";
			path += y + "/" + m + "/" + d + "/";

			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			int position = fileName.lastIndexOf(".");
			String extension = fileName.substring(position);
			String fileId = UUIDGenerator.getUUID();
			String name = fileId + extension;
			path += name;
			File savedFile = new File(savePath, name);
			FileInputStream fis = new FileInputStream(file);
			fos = new FileOutputStream(savedFile);
			bos = new BufferedOutputStream(fos);
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			map.put("flag", flag == true ? "1" : "0");
			map.put("savepath", path);
			map.put("filename", fileName);
			map.put("fileid", fileId);

		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		} finally {
			if (file != null) {
				file.delete();
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}

		return map;
	}

	/**
	 * new文件名= 时间 + 全球唯一编号
	 * 
	 * @param fileName
	 *            old文件名
	 * @return new文件名
	 */
	public static String generateFileName(String fileName) {
		String uuid = UUID.randomUUID().toString();
		int position = fileName.lastIndexOf(".");
		String extension = fileName.substring(position);
		return uuid + extension;
	}

	public static String getTimePath(String dir) {
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
		SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
		SimpleDateFormat sdf3 = new SimpleDateFormat("dd");
		String y = sdf1.format(new Date());
		String m = sdf2.format(new Date());
		String d = sdf3.format(new Date());

		return "attached/" + dir + "/" + y + "/" + m + "/" + d + "/";
	}
}
